package com_fit.springboot_fit.security;


import com_fit.springboot_fit.entity.AdminUser;
import com_fit.springboot_fit.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    @Lazy
    private AdminUserService userService;

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {

        System.out.println("===== 进入 loadUserByUsername 方法 ====="); // 首行打印标识
        System.out.println("loginName: " + loginName);


        AdminUser user = userService.findByLoginName(loginName)
                .orElseThrow(() -> new UsernameNotFoundException("loginName:"+loginName+"用户名不存在1"));

        // 检查用户状态
        if (AdminUser.YesNoEnum.yes.equals(user.getIsLock())) {
            throw new UsernameNotFoundException("用户已被锁定");
        }

        if (AdminUser.YesNoEnum.no.equals(user.getIsShow())) {
            throw new UsernameNotFoundException("用户不可用");
        }

        // 获取用户权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 这里简化处理，实际应根据用户权限添加对应的角色或权限
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        // 如果是超级管理员，添加管理员角色
        if (AdminUser.YesNoEnum.yes.equals(user.getIsAdmin())) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }

        return new User(
                user.getLoginName(),
                user.getPasswd(),
                authorities
        );
    }


}
